<template>
	<el-select
		:value="value"
		:filterable="true"
		:remote="true"
		:reserve-keyword="true"
		:clearable="clearable"
		:remote-method="remoteMethod"
		:loading="loading"
		:placeholder="placeholder"
		@change="change"
	>
		<el-option
			v-for="item in options"
			:key="item.teacherId"
			:label="`${item.userName}-${item.schoolName||'无'}-${item.dptName||'无'}`"
			:value="item.teacherId"
		/>
	</el-select>
</template>

<script>
	import ecsApi from "@rc/apis/ecs/index.mjs";

	export default {
		props: {
			// teacherId,支持v-model
			value: {
				type: String,
				default: ""
			},
			placeholder: {
				type: String,
				default: "请输入授课老师"
			},
			clearable: {
				type: Boolean,
				default: false
			},
			teacherAvlstatus: {
				//教师状态Y:可用;N:不可用;""全部
				type: String,
				default: ""
			}
		},
		data() {
			return {
				loading: false,
				options: []
			};
		},
		watch: {
			value: {
				handler(val) {
					if (val && !this.options.some((i) => i.teacherId === val)) {
						// 当有选中id却找不到对应匹配项时，检索该id详情用于显示
						this.loading = true;
						ecsApi.queryTeacherInfo({
							data: {
								teacherId: val
							},
							success: (data) => {
								this.options = data ? [data] : [];
								this.$emit("ready", this.options);
							},
							complete: () => {
								this.loading = false;
							}
						});
					}
				},
				immediate: true
			}
		},
		methods: {
			/**
			 * 远程搜索 支持姓名和ID查询
			 */
			remoteMethod(userName = "") {
				if (!userName) {
					return;
				}
				this.loading = true;
				ecsApi.queryTeacherList({
					data: {
						userName,
						teacherAvlstatus: this.teacherAvlstatus
					},
					success: ({ data }) => {
						this.options = data;
						this.$emit("ready", this.options);
					},
					complete: () => {
						this.loading = false;
					}
				});
			},
			change(data) {
				this.$emit("input", data);
				this.$emit("change", data);
			},
			api_getOptions() {
				return this.options;
			}
		}
	};
</script>
